package com.hspedu.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.seckill.entity.User;
import com.hspedu.seckill.exception.GlobalException;
import com.hspedu.seckill.mapper.UserMapper;
import com.hspedu.seckill.model.constant.RedisCacheConstant;
import com.hspedu.seckill.model.constant.RespBeanEnum;
import com.hspedu.seckill.model.result.RespBean;
import com.hspedu.seckill.model.vo.LoginVo;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.utils.CookieUtil;
import com.hspedu.seckill.utils.MD5Util;
import com.hspedu.seckill.utils.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.security.util.Password;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author: xujiabing
 * @date: 2024-10-02 20:39
 * @description 用户登录相关业务类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 登录校验方法
     * @param loginVo
     * @param request
     * @param response
     * @return
     */
    @Override
    public RespBean doLogin(LoginVo loginVo,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        //接收到手机号和密码[中间密码,前端md5(原始密码 + salt1)]
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

//        //非空校验
//        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password)) {
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
//        //校验手机号码是否合法
//        if (!ValidatorUtil.isMobile(mobile)) {
//            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
//        }
        //以上逻辑被注解校验取代
        //校验用户是否存在
        User user = userMapper.selectById(mobile);
        if (Objects.isNull(user)) {
            //return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            //改为全局异常处理机制
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //校验密码是否正确
        if (!MD5Util.midPassToDBPass(password, user.getSlat())
                .equals(user.getPassword())) {
            //return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //登录成功

        //给每个用户生成唯一 ticket ,并存放到cookie中
        String ticket = UUIDUtil.uuid();
        //v1.0 将 user信息放入到seesion中 ,ticket 作为key
        //request.getSession().setAttribute(ticket,user);

        //v2.0 实现分布式session,将用户信息直接存储在redis中
        redisTemplate.opsForValue().set("user:" + ticket,user);

        //将ticket ,存放到cookie中
        CookieUtil.setCookie(request,response,"userTicket",ticket);

        //让模拟用户登录接口得到ticket
        return RespBean.success(ticket);

    }

    /**
     * @description: 通过 ticket 获取用户信息
     * @author: xujiabing
     * @date: 2024-10-03 19:18
     * @param: userTicket
     * @param: request
     * @param: response
     * @return: com.hspedu.seckill.entity.User
     */
    @Override
    public User getUserByCookie(String userTicket,
                                HttpServletRequest request,
                                HttpServletResponse response) {
        if (StringUtils.isBlank(userTicket)) {
            return null;
        }
        //从redis中获取用户信息
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);

        if (!Objects.isNull(user)) {
            //重新设置cookie信息,刷新session失效时间,默认30分钟
            CookieUtil.setCookie(request,response,"userTicket",userTicket);
        }
        return user;
    }

    /**
     * @description: 更新用户密码-同时删除redis缓存，用户重新登录，并刷新redis缓存
     * @author: xujiabing
     * @date: 2024-11-17 20:54
     * @param: userTicket 用户凭证
     * @param: password 明文密码
     * @param: request
     * @param: response
     * @return: RespBean
     */
    @Override
    public RespBean updatePassword(String userTicket, String password
            , HttpServletRequest request, HttpServletResponse response) {
        User user = getUserByCookie(userTicket, request, response);
        //redis 没有查询到，用户没有登录
        if (Objects.isNull(user)) {
            throw new GlobalException(RespBeanEnum.MOBILE_NOT_EXIST);
        }
        //更新用户密码
        user.setPassword(MD5Util.inputPassToDBPass(password,user.getSlat()));
        int update = userMapper.updateById(user);
        if (update == 1) {
            //更新成功，同时删除redis缓存数据
            redisTemplate.delete(RedisCacheConstant.USER + userTicket);
            return RespBean.success();
        }

        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_FAIL);
    }


}
